package com.yb.xczx.cloud.auth.handler;

import com.alibaba.fastjson2.JSON;
import com.yb.core.constant.RedisKeyConstant;
import com.yb.core.enums.LoginTypeEnum;
import com.yb.core.model.XczxResult;
import com.yb.core.util.XczxTokenGenerator;
import com.yb.xczx.cache.manager.api.XczxStringCacheManager;
import com.yb.xczx.cloud.auth.bean.LoginSuccessResult;
import com.yb.xczx.cloud.auth.bean.XczxAbstractAuthenticationToken;
import com.yb.xczx.cloud.auth.bean.XczxSysUser;
import com.yb.xczx.cloud.auth.bean.XczxUserPassAuthenticationToken;
import com.yb.xczx.cloud.auth.util.CacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/19 12:30
 * FileName: LoginSuccessHandler
 * Description:
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

        @Autowired
        XczxStringCacheManager xczxStringCacheManager;
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse
        response, Authentication authentication) throws IOException, ServletException {

            if(authentication instanceof XczxAbstractAuthenticationToken){
                XczxAbstractAuthenticationToken authenticationToken= (XczxAbstractAuthenticationToken) authentication;
                String loginAccessToken = authenticationToken.getLoginAccessToken();
                LoginSuccessResult result = new LoginSuccessResult();
                result.setLoginAccessToken(loginAccessToken);

                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.getWriter().write(XczxResult.success(result).toJSON());
                return;
            }

            XczxSysUser xczxSysUser= (XczxSysUser) authentication.getPrincipal();
            xczxSysUser.setLoginType(LoginTypeEnum.USER_PASS.getLoginType());
            String loginAccessToken = xczxStringCacheManager.getString(String.format(RedisKeyConstant.LOGIN_USER_ACCESS_TOKEN_KEY, xczxSysUser.getUsername()));

            if(!StringUtils.hasText(loginAccessToken)){

                loginAccessToken = XczxTokenGenerator.generate(xczxSysUser.getUsername());
                xczxSysUser.setLoginAccessToken(loginAccessToken);
                Map<String,String> map=new HashMap<>();
                map.put(String.format(RedisKeyConstant.LOGIN_USER_ACCESS_TOKEN_KEY,xczxSysUser.getUsername()), loginAccessToken);
                map.put(String.format(RedisKeyConstant.LOGIN_USER_DETAIL_KEY,loginAccessToken), JSON.toJSONString(xczxSysUser));
                xczxStringCacheManager.multiSet(map);

            }
            String targetUrlKey = request.getParameter("targetUrlKey");
            if(StringUtils.hasText(targetUrlKey)){
                String targetUrl = CacheUtil.targetUrlMap.get(targetUrlKey);
                if(StringUtils.hasText(targetUrl)) {
                    response.sendRedirect(targetUrl + "&access_token=" + loginAccessToken);
                    return;
                }else{
                    response.sendRedirect("/?access_token="+loginAccessToken);
                    return;
                }
            }
        };
}
